import fs from "fs"
import path from "path"
import os from "os"
import Wallpaper from "../model/wallPaper.model.js"
const { APP_PORT, MYSQL_HOST } = process.env
import { __dirname } from "../utils/common.js"

class WallpaperService {

  // 获取随机图片 http 地址
  async getImg(israndom) {
    let imgUrl = ''
    let Path = path.join(__dirname(import.meta.url), '../static/wallpaper')
    // 本地所有图片的名称集合
    let imgnameLocalArr = fs.readdirSync(Path)
    // 获取随机图片的信息
    const getRanImgName = async list => {
      return new Promise(resolve => {
        let imgname = ""
        if (list && list.length > 0) {
          const index = list && list.length > 0 ? Math.floor(Math.random() * list.length) : undefined
          imgname = list[index]
          fs.stat(Path + '/' + imgname, (err, stats) => {
            if (err) throw err
            const size = (Number(stats.size)/1024).toFixed(2)
            resolve({ imgname, size  })
          })
        }
      })
    }
    if (imgnameLocalArr && imgnameLocalArr.length > 0) {
      let imgFileInfo = ''
      // 不重复
      if (israndom === '1') {
        // 数据库中存在的图片名称集合
        let imgnameDatabase = await Wallpaper.findAll({ attributes: ['imgname'] })
        if (imgnameDatabase && imgnameDatabase.length > 0) {
          imgnameDatabase = imgnameDatabase.map(item => item.dataValues.imgname)
          const isExist = imgnameLocalArr.every(item => imgnameDatabase.includes(item))
          // imgnameDatabase 包含 imgnameLocalArr 时
          if (isExist) {
            await Wallpaper.destroy({ truncate: true })
            imgFileInfo = await getRanImgName(imgnameLocalArr)
          } else {
            // 本地图片名称集合中不存在数据库中的图片名称集合
            let list = imgnameLocalArr.filter(item => !imgnameDatabase.includes(item))
            imgFileInfo = await getRanImgName(list)
          }
        } else {
          imgFileInfo = await getRanImgName(imgnameLocalArr)
        }
        await Wallpaper.create({ imgname: imgFileInfo.imgname, size: imgFileInfo.size })
      }
      // 可重复
      else {
        imgFileInfo = await getRanImgName(imgnameLocalArr)
      }
      let ip = "127.0.0.1"
      if (os.type() === "Linux") ip = MYSQL_HOST
      imgUrl = `http://${ip}:${APP_PORT}/wallpaper/${imgFileInfo.imgname}`
    }
    return imgUrl
  }

}

export default new WallpaperService()